from app import models
from app.util.time import current_time_string
from app.util.id_util import uuid


def global_int(key, value=None):
    qs = models.GlobalData.objects.filter(key=key)
    if len(qs) == 0:
        d = models.GlobalData()
        d.key = key
        d.value = '0'
        d.save()
    else:
        d = qs[0]

    if value or value in ['0', 0]:
        d.value = str(value)
        d.save()
        return None
    else:
        return int(d.value)


def renew_server_version():
    qs = models.GlobalData.objects.filter(key='server_version')
    try:
        gd = qs[0]
    except:
        gd = models.GlobalData()
        gd.key = 'server_version'
    gd.value = current_time_string()
    gd.save()


def server_version():
    qs = models.GlobalData.objects.filter(key='server_version')
    try:
        gd = qs[0]
    except:
        gd = models.GlobalData()
        gd.key = 'server_version'
        gd.value = current_time_string() + '_' + uuid()
        gd.save()
    return gd.value
